/**
 * Created by Forcs on 16/4/14.
 */

var co = require('co');

var Products = require('../models/Products');

var ProductController = function () {};

ProductController.prototype.saveProduct = function (req, res) {
  var body = req.body;
  Products.$manager.addProduct(
    {
      code: body.code,
      name: body.name,
      token: body.token,
      biz: body.biz
    },
    function (err, result) {
      if (err) {
        res.json({
          code: 0,
          msg: err.toString()
        });
        return;
      }

      res.json({
        code: 1,
        msg: 'ok',
        result: result
      });
    }
  );
};

ProductController.prototype.saveCategory = function (req, res) {
  var productCode = req.params.productcode;
  var body = req.body;
  Products.$manager.addCategory(
    productCode,
    {
      code: body.code,
      name: body.name
    },
    function (err, result) {
      if (err) {
        res.json({
          code: 0,
          msg: err.toString()
        });
        return;
      }

      res.json({
        code: 1,
        msg: 'ok',
        result: result
      });

    }
  );
};

ProductController.prototype.saveContent = function (req, res) {
  var productCode = req.params.productcode;
  var categoryCode = req.params.categorycode;
  var body = req.body;

  Products.$manager.addContent(
    productCode,
    categoryCode,
    {
      code: body.code,
      name: body.name
    },
    function (err, result) {
      if (err) {
        res.json({
          code: 0,
          msg: err.toString()
        });
        return;
      }

      res.json({
        code: 1,
        msg: 'ok',
        result: result
      });
    }
  );
};

ProductController.prototype.onRouting = function (router) {
  router.post('/add', this.saveProduct);
  router.post('/add/:productcode', this.saveCategory);
  router.post('/add/:productcode/:categorycode', this.saveContent);
};

module.exports = ProductController;
